<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item>
        <el-date-picker
          v-model="entryDate"
          clearable
          value-format="yyyy-MM-dd"
          type="daterange"
          placeholder="选择日期"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 360px;"
          @change="handleDateChange"
        />
      </el-form-item>

      <el-form-item style="margin-left: 28px;">
        <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px;">
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
        <el-button type="warning" icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleDelete"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog ref="form" :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="schoolyear" :rules="rules" label-width="80px" size="mini">
        <el-form-item label="开始时间" prop="createTime">
          <el-date-picker
            v-model="schoolyear.createTime"
            clearable
            type="date"
            placeholder="选择日期"
            size="small"
            style="width:100%"
            value-format="yyyy-MM-dd"
            :disabled="schoolyear.status == '0'"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="schoolyear.endTime"
            clearable
            type="date"
            placeholder="选择日期"
            size="small"
            style="width:100%"
            value-format="yyyy-MM-dd"
            :disabled="schoolyear.status == '0'"
          />
        </el-form-item>

        <el-form-item prop="status">
          <span slot="label">
            <el-tooltip content="发布后不允许修改内容" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
            状态
          </span>
          <el-radio-group v-model="schoolyear.status">
            <el-radio key="1" label="1">禁用</el-radio>
            <el-radio key="0" label="0">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="margin-left: 50px;">
          <el-button type="primary" @click="add('schoolyear')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column type="index" label="序号" align="center" /> -->
      <el-table-column prop="term" label="学年学期" align="center" />
      <el-table-column prop="createTime" label="开始时间" align="center" />
      <el-table-column prop="endTime" label="结束时间" align="center" />
      <el-table-column prop="state" label="状态" align="center">

        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">启用</span>
          <span v-if="scope.row.status == 1">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="update(scope.row.id)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deleteById(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { add, update, page, deleteById, selectById } from '@/api/schoolyear.js'
import { parseTime } from '@/utils'
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      // 非单个禁用
      single: true,
      // 遮罩层
      loading: true,
      buttonState: '', // 存储按钮的状态
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      title: '',
      dialogVisible: false,
      queryParams: {
        status: '',
        createTime: '', // 添加开始时间字段
        endTime: '' // 添加结束时间字段
      },
      entryDate: [], // 用于v-model绑定日期选择器的值
      value: {
      },
      schoolyear: {
        status: '',
        createTime: '',
        endTime: ''
      },
      rules: {
        createTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      },
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      // options: [{
      //   value: '2024-2025-1',
      //   label: '2024-2025-1'
      // }, {
      //   value: '2023-2024-2',
      //   label: '2023-2024-2'
      // }, {
      //   value: '2023-2024-1',
      //   label: '2023-2024-1'
      // }, {
      //   value: '2022-2023-2',
      //   label: '2022-2023-2'
      // }, {
      //   value: '2022-2023-1',
      //   label: '2022-2023-1'
      // }],
      tableKey: 0,
      list: null,
      total: 0
    }
  },
  computed: {

    ...mapState(['name'])
  },

  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },

  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 表单重置
    reset() {
      this.schoolyear = {
        createTime: undefined,
        endTime: undefined,
        status: '1'
      }
    },
    /** 修改表单按钮操作 */
    handlechange(row) {
      this.reset()
      this.dialogVisible = true
      this.title = '修改表单'
    },
    /** 导出按钮操作 */
    handleDelete(row) {
      // const userIds = row.userId || this.ids
      // this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
      //   return delUser(userIds)
      // }).then(() => {
      //   this.getList()
      //   this.$modal.msgSuccess('删除成功')
      // }).catch(() => { })
    },
    handleExport() {
      // this.download('system/user/export', {
      //   ...this.queryParams
      // }, `user_${new Date().getTime()}.xlsx`)
    },
    // 查询分页数据
    page() {
      this.loading = true
      const requestData = {
        status: this.queryParams.status,
        createTime: this.queryParams.createTime,
        endTime: this.queryParams.endTime,
        current: this.current,
        pageSize: this.pageSize
      }

      page(requestData).then((res) => {
        this.totalCount = res.data.total
        this.tableData = res.data.records
        this.loading = false
      }).catch((error) => {
        // 处理错误情况
        console.error('Error fetching data:', error)
      })
    },
    handleAdd() {
      this.reset()
      this.dialogVisible = true
      this.title = '新增表单'
    },
    handleDateChange(val) {
      if (val) {
        this.queryParams.createTime = val[0] // 开始时间
        this.queryParams.endTime = val[1] // 结束时间
      } else {
        this.queryParams.createTime = ''
        this.queryParams.endTime = ''
      }
    },

    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },
    // 重置方法
    clear() {
      this.queryParams.status = ''
      this.entryDate = []
      this.page()
    },
    // 添加数据
    add() {
      let operator

      if (this.schoolyear.id) {
        // 修改
        operator = update(this.schoolyear)
      } else {
        operator = add(this.schoolyear)
      }

      operator.then((resp) => {
        if (resp.code == '1') {
          this.dialogVisible = false
          this.page()
          this.$message({ message: '恭喜你，保存成功', type: 'success' })
        } else {
          this.$message.error(resp.msg)
        }
      })
    },
    update(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      this.title = '修改表单'
      // 2. 发送请求获取学年信息并根据状态决定表单是否禁用
      selectById(id).then((result) => {
        if (result.code == 1) {
          this.schoolyear = result.data
        }
      })
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    // 删除学年信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 2. 发送AJAX请求
        deleteById(id).then((resp) => {
          if (resp.code == 1) {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    ...mapMutations('schoolmanage', ['getname']),
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped>
/* 全局CSS 或者在<style scoped>内 */
.el-form-item .is-disabled .el-input__inner,
.is-disabled .el-date-editor.el-input__inner {
  background-color: #f5f7fa;
  /* 变更输入框背景色 */
  color: #c0c4cc;
  /* 变更文字颜色 */
  cursor: not-allowed;
  /* 更改鼠标指针形状 */
}

/* 如果需要单独针对学期学年（el-select）调整样式 */
.el-form-item .is-disabled .el-select .el-input__inner {
  /* 在这里添加特定于el-select的样式 */
}
</style>
